package com.thinkingcoder.tcrpc.core.registry.tc;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 介入 TcRegistry 的实现类
 */
@Slf4j
public class TcHealthChecker {

    ScheduledExecutorService providerExecutor = null;
    ScheduledExecutorService consumerExecutor = null;

    public void start() {
        log.info(" ===>>> [TcRegistry] : Start with health checker.");
        // 开启一个线程数为1的定时任务线程池
        providerExecutor = Executors.newScheduledThreadPool(1);
        consumerExecutor = Executors.newScheduledThreadPool(1);
    }

    public void stop() {
        log.info(" ===>>> [TcRegistry] : Stop with health checker.");
        gracefulShutdown(providerExecutor);
        gracefulShutdown(consumerExecutor);
    }

    private void gracefulShutdown(ScheduledExecutorService executorService) {
        // 优雅停机
        executorService.shutdown();
        try {
            executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
            if (!executorService.isTerminated()) {
                // 立即停机
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            // ignore
        }
    }

    public void providerCheck(Callback callback) {
        // 对 provider 注册的服务实例进行保活
        providerExecutor.scheduleAtFixedRate(() -> {
            try {
                callback.call();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }, 5_000, 5_000, TimeUnit.MILLISECONDS);
    }

    public void consumerCheck(Callback callback) {
        consumerExecutor.scheduleWithFixedDelay(() -> {
            try {
                callback.call();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        }, 1000, 5000, TimeUnit.MILLISECONDS);
    }
}
